package com.apes.fico.engine.strategy;

import com.apes.fico.engine.ElementStrategy;
import com.apes.fico.engine.FicoUtil;
import com.apes.fico.engine.model.ElementChart;
import com.apes.framework.jpa.ApesBean;
import com.apes.framework.plugin.soe.metadata.BusinessField;
import com.apes.framework.util.JpaUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 功能：通用要素策略
 *
 * @author xul
 * @create 2019-01-30 16:43
 */
@Component
public class GeneralElementStrategyImpl implements ElementStrategy {

    @Override
    public String getDescription() {
        return "通用策略";
    }

    @Override
    public boolean execute(Map<String, Object> context, ElementChart ec) {
        String entityName = FicoUtil.getNodeName(context);
        String fieldName = getFieldName(ec, entityName);
        Object entity = FicoUtil.eval(entityName + "." + fieldName, context, null, false, Throwable::getMessage);
        if (entity == null){
            entity = FicoUtil.eval(fieldName, context, null, false, Throwable::getMessage);
        }
        if (entity != null && entity instanceof ApesBean) {
            String businessId = JpaUtil.getIdToStr((ApesBean) entity);
            if (businessId == null) return false;
            /*增加支持要数值用分隔符隔开*/
            List elementValueList =  Arrays.asList(ec.getElementValue().split(","));
            long iLen = elementValueList.stream().filter(elementValue ->   businessId.equals(elementValue)).count();
            if (iLen > 0) return true;
        }
        return false;
    }

    private String getFieldName(ElementChart ec, String entityName) {
        BusinessField businessField = ec.getElement().getBusinessField();
        if (!StringUtils.isEmpty(entityName)) {
            String code = businessField.businessTypeCode(entityName);
            if (code != null) return code;
        }
        return businessField.getId();
    }

}
